<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category    Gold
 * @package     Gold_Repay
 * @author   $Id$
 */
require_once 'Phoenix/Worldpay/controllers/ProcessingController.php';
class Gold_Repay_Worldpay_ProcessingController extends Phoenix_Worldpay_ProcessingController
{    
    protected function _getCatalog()
	{
	  Mage::getSingleton('catalog/session');
	}
	
	protected function _getRepay()
	{
	 return Mage::getSingleton('repay/session');
	}
	
    public function redirectAction()
    {
	   $orderId = (int) $this->getRequest()->getParam('order_id');
       if (!$orderId)
       {
       	$this->_getRepay()->clear();//clear repay session
       	parent::redirectAction();
       }
       else 
       {
			try {
				$this->_getRepay()->setRepay(true);//This is repay action
       			$this->_getRepay()->setOrderId($orderId);
				$order = Mage::getModel('sales/order');
				$order->loadByAttribute('entity_id',$orderId);
				if (!$order->getId()) {
					Mage::throwException('No order for processing found');
				}
				if ($order->getState() != Mage_Sales_Model_Order::STATE_PENDING_PAYMENT) {
					$order->setState(
						Mage_Sales_Model_Order::STATE_PENDING_PAYMENT,
						$this->_getPendingPaymentStatus(),
						Mage::helper('worldpay')->__('Customer was redirected to Worldpay.')
					)->save();
				}

				$this->loadLayout();
				$layout = $this->getLayout();
				//$update = $layout->getUpdate();
				//$update->load('repay_worldpay_processing_redirect');
				//$update->removeHandle('worldpay_processing_redirect');
				//$layout->generateXml();
		        //$layout->generateBlocks();
		        //$output = $layout->getOutput();	
		        $this->getResponse()->appendBody('<html><body>'.$layout->createBlock('repay/worldpay_redirect','worldpay_redirect')->setOrder($order)->setTemplate('worldpay/redirect.phtml')->toHtml().'</body></html>');
				return;
			} catch (Mage_Core_Exception $e) {
				$this->_getCatalog()->addError($e->getMessage());
			} catch(Exception $e) {
				$this->_debug('Worldpay error: ' . $e->getMessage());
				Mage::logException($e);
			}
			$this->_redirect('checkout/cart');
		}
	}
}